import 'dart:math';

import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:xcite/core/utils/ali.dart';

import '../../core/providers/private_chat_provider.dart';
import '../../core/providers/team_provider.dart';
import '../../core/providers/user_provider.dart';
import '../../core/utils/chat_helper.dart';
import '../../core/utils/popup_helper.dart';
import '../../core/utils/toast_helper.dart';

class CommunicationCenterScreen extends ConsumerStatefulWidget {
  const CommunicationCenterScreen({super.key});

  @override
  ConsumerState<CommunicationCenterScreen> createState() =>
      _CommunicationCenterScreenState();
}

class _CommunicationCenterScreenState
    extends ConsumerState<CommunicationCenterScreen> {
  late PageController _teamPageController;
  int _currentTeamIndex = 0;

  @override
  void initState() {
    super.initState();
    _teamPageController = PageController();
  }

  @override
  void dispose() {
    _teamPageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final currentUser = ref.watch(currentUserProvider);

    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/common_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child:
              currentUser == null ? _buildLoginPrompt() : _buildMainContent(),
        ),
      ),
    );
  }

  Widget _buildLoginPrompt() {
    return [
      Spacer(),
      Container(
        width: 120.w,
        height: 120.w,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/logo.png'),
            fit: BoxFit.contain,
          ),
        ),
      ).center(),
      SizedBox(height: 24.h),
      Text(
        'Please login to access messages',
        style: TextStyle(
          fontSize: 18.sp,
          color: Colors.white,
          fontWeight: FontWeight.w600,
          fontFamily: 'PoetsenOne',
        ),
      ).center(),
      SizedBox(height: 32.h),
      Container(
        width: 200.w,
        height: 48.h,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(24.r),
        ),
        child:
            Text(
              'Go to Login',
              style: TextStyle(
                fontSize: 16.sp,
                color: Colors.black,
                fontWeight: FontWeight.w600,
                fontFamily: 'PoetsenOne',
              ),
            ).center(),
      ).center().inkWell(
        onTap: () {
          PopupHelper.showLoginDialog(
            context,
            onLoginPressed: () {
              GoRouter.of(context).push('/login');
            },
            onCancelPressed: () {},
          );
        },
      ),
      Spacer(),
    ].toColumn();
  }

  Widget _buildMainContent() {
    return [
      _buildTopBar(),
      Expanded(
        child: SingleChildScrollView(
          child:
              [
                SizedBox(height: 6.h),
                _buildSocialActions(),
                SizedBox(height: 32.h),
                _buildFriendsUpdates(),
                SizedBox(height: 28.h),
                _buildChatSection(),
                SizedBox(height: 20.h),
                _buildGroupSection(),
                SizedBox(height: 120.h),
              ].toColumn(),
        ),
      ),
    ].toColumn();
  }

  Widget _buildTopBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child:
          [
            Text(
              'Message',
              style: TextStyle(
                fontSize: 24.sp,
                fontWeight: FontWeight.bold,
                color: Colors.black,
                fontFamily: 'PoetsenOne',
              ),
            ),
            Spacer(),
            Container(
              width: 30.w,
              height: 30.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.black,
              ),
              child:
                  Icon(
                    AliIcons.iconClean,
                    size: 18.sp,
                    color: Colors.white,
                  ).center(),
            ).inkWell(onTap: _showClearMessagesDialog),
          ].toRow(),
    );
  }

  Widget _buildSocialActions() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: [
        _buildSocialActionItem('Like', 'assets/resources/like_button.png'),
        _buildSocialActionItem('Follow', 'assets/resources/follow_button.png'),
        _buildSocialActionItem('Fan', 'assets/resources/fan_button.png'),
      ].toRow(mainAxisAlignment: MainAxisAlignment.spaceEvenly),
    );
  }

  Widget _buildSocialActionItem(String title, String imagePath) {
    return [
      Container(
        width: 68.w,
        height: 68.h,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(imagePath),
            fit: BoxFit.contain,
          ),
        ),
      ),
      SizedBox(height: 2.h),
      Text(
        title,
        style: TextStyle(
          fontSize: 15.sp,
          color: Colors.black,
          fontWeight: FontWeight.w600,
          fontFamily: 'PoetsenOne',
        ),
      ),
    ].toColumn().inkWell(
      onTap: () {
        if (title == 'Like') {
          context.push('/preference-showcase');
        } else if (title == 'Follow') {
          context.push('/social-connection/following');
        } else if (title == 'Fan') {
          context.push('/social-connection/followers');
        }
      },
    );
  }

  Widget _buildFriendsUpdates() {
    final currentUser = ref.watch(currentUserProvider);
    final userNotifier = ref.read(userProvider.notifier);
    final allUsers = userNotifier.getAllDefaultUsers();
    final otherUsers =
        allUsers.where((user) => user.id != currentUser?.id).toList();
    final random = Random();

    return [
      Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        child: Text(
          'Friends Updates',
          style: TextStyle(
            fontSize: 24.sp,
            fontWeight: FontWeight.bold,
            color: Colors.white,
            fontFamily: 'PoetsenOne',
          ),
        ),
      ),
      SizedBox(height: 16.h),
      Container(
        margin: EdgeInsets.symmetric(horizontal: 16.w),
        padding: EdgeInsets.only(left: 1.w, right: 3.w),
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/friend_container.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: AspectRatio(
          aspectRatio: 374 / 112,
          child: SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
            child: [
              for (final user in otherUsers)
                _buildFriendItem(user, random.nextBool()),
            ].toRow(mainAxisAlignment: MainAxisAlignment.start),
          ),
        ),
      ),
    ].toColumn(crossAxisAlignment: CrossAxisAlignment.start);
  }

  Widget _buildFriendItem(dynamic user, bool isOnline) {
    return Container(
      margin: EdgeInsets.only(right: 16.w),
      child:
          [
            Stack(
              children: [
                Container(
                  width: 62.w,
                  height: 62.w,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    image: DecorationImage(
                      image: AssetImage(user.avatar),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                if (isOnline)
                  Positioned(
                    right: 2.w,
                    top: 2.w,
                    child: Container(
                      width: 12.w,
                      height: 12.w,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: Colors.green,
                        border: Border.all(color: Colors.white, width: 2),
                      ),
                    ),
                  ),
              ],
            ),
            Text(
              user.username,
              style: TextStyle(
                fontSize: 12.sp,
                fontFamily: 'PoetsenOne',
                color: Colors.black,
                fontWeight: FontWeight.w500,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ].toColumn(),
    ).inkWell(
      onTap: () {
        ChatHelper.handleUserAvatarTap(
          context: context,
          ref: ref,
          targetUserId: user.id,
        );
      },
    );
  }

  Widget _buildChatSection() {
    final currentUser = ref.watch(currentUserProvider);
    final conversations = ref.watch(
      userConversationsProvider(currentUser?.id ?? ''),
    );

    return [
      Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        child: Text(
          'Chat',
          style: TextStyle(
            fontSize: 24.sp,
            fontWeight: FontWeight.bold,
            color: Colors.white,
            fontFamily: 'PoetsenOne',
          ),
        ),
      ),
      SizedBox(
        height: 166.h,
        child: SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: [
            for (final conversation in conversations)
              _buildChatItem(conversation, currentUser?.id ?? ''),
          ].toRow(mainAxisAlignment: MainAxisAlignment.start),
        ),
      ),
    ].toColumn(crossAxisAlignment: CrossAxisAlignment.start);
  }

  Widget _buildChatItem(dynamic conversation, String currentUserId) {
    final isCurrentUserOne = conversation.participantOneId == currentUserId;
    final otherUserAvatar =
        isCurrentUserOne
            ? conversation.participantTwoAvatar
            : conversation.participantOneAvatar;

    return Container(
      width: 115.w,
      margin: EdgeInsets.only(right: 12.w, top: 25.h),
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/resources/chat_card.png'),
                fit: BoxFit.fill,
              ),
            ),
            child: AspectRatio(
              aspectRatio: 115 / 135,
              child:
                  [
                    SizedBox(height: 50.h),
                    Text(
                      _formatTime(conversation.lastMessageTime),
                      style: TextStyle(fontSize: 12.sp, color: Colors.black),
                    ).center(),
                    SizedBox(height: 8.h),
                    Expanded(
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 8.w),
                        child: Text(
                          conversation.lastMessage,
                          style: TextStyle(
                            fontSize: 10.sp,
                            color: Colors.black,
                          ),
                          maxLines: 3,
                          overflow: TextOverflow.ellipsis,
                          textAlign: TextAlign.left,
                        ),
                      ),
                    ),
                    SizedBox(height: 8.h),
                  ].toColumn(),
            ),
          ),
          Positioned(
            top: -25.h,
            left: (115.w - 62.w) / 2,
            child: Stack(
              clipBehavior: Clip.none,
              children: [
                Container(
                  width: 62.w,
                  height: 62.w,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(color: Colors.black, width: 1.w),
                    image: DecorationImage(
                      image: AssetImage(otherUserAvatar),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                if (conversation.unreadCount > 0)
                  Positioned(
                    right: -2.w,
                    bottom: -2.w,
                    child: Container(
                      padding: EdgeInsets.all(4.w),
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: Color(0xFF2AB061),
                      ),
                      child: Text(
                        conversation.unreadCount.toString(),
                        style: TextStyle(
                          fontSize: 12.sp,
                          fontFamily: 'PoetsenOne',
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    ).inkWell(
      onTap: () {
        ChatHelper.handleChatListTap(
          context: context,
          conversationId: conversation.conversationId,
          otherUserId:
              conversation.participantOneId == currentUserId
                  ? conversation.participantTwoId
                  : conversation.participantOneId,
        );
      },
    );
  }

  Widget _buildGroupSection() {
    final currentUser = ref.watch(currentUserProvider);
    final userTeams = ref.watch(userTeamsProvider(currentUser?.id ?? ''));

    return [
      Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        child: Text(
          'Group spring outing',
          style: TextStyle(
            fontSize: 24.sp,
            fontWeight: FontWeight.bold,
            color: Colors.white,
            fontFamily: 'PoetsenOne',
          ),
        ),
      ),
      SizedBox(height: 6.h),
      _buildTeamCarousel(userTeams),
    ].toColumn(crossAxisAlignment: CrossAxisAlignment.start);
  }

  Widget _buildTeamCarousel(List<dynamic> teams) {
    return teams.isEmpty
        ? _buildEmptyTeamsPlaceholder()
        : _buildTeamsPageView(teams);
  }

  Widget _buildEmptyTeamsPlaceholder() {
    return SizedBox(
      height: 200.h,
      child: Center(
        child: Text(
          'No teams joined yet',
          style: TextStyle(fontSize: 16.sp, color: Colors.grey),
        ),
      ),
    );
  }

  Widget _buildTeamsPageView(List<dynamic> teams) {
    return AspectRatio(
      aspectRatio: 374 / 217,
      child: PageView.builder(
        controller: _teamPageController,
        onPageChanged: _onTeamPageChanged,
        itemCount: teams.length,
        itemBuilder: (context, index) => _buildTeamCard(teams[index]),
      ),
    );
  }

  void _onTeamPageChanged(int index) {
    if (mounted) {
      setState(() {
        _currentTeamIndex = index;
      });
    }
  }

  Widget _buildTeamCard(dynamic team) {
    final currentUser = ref.watch(currentUserProvider);

    final userNotifier = ref.read(userProvider.notifier);
    final allUsers = userNotifier.getAllDefaultUsers();
    final creator = allUsers.firstWhere(
      (u) => u.id == team.creatorId,
      orElse: () => allUsers.first,
    );

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/team_card.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: [
              Container(
                width: 128.w,
                height: 56.h,
                decoration: BoxDecoration(color: Colors.transparent),
              ).inkWell(
                onTap: () {
                  GoRouter.of(context).push('/create-team');
                },
              ),
              Spacer(),
              [
                SizedBox(width: 10.w),
                Container(
                  width: 128.w,
                  height: 128.w,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8.r),
                    image: DecorationImage(
                      image: AssetImage(team.coverImage),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                SizedBox(width: 12.w),
                Expanded(
                  child: [
                    Text(
                      team.teamName,
                      style: TextStyle(
                        fontSize: 18.sp,
                        fontFamily: 'PoetsenOne',
                        fontWeight: FontWeight.bold,
                        color: Colors.black,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    SizedBox(height: 8.h),
                    [
                      Container(
                        width: 20.w,
                        height: 20.w,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: Color(0xFFFDF5E1),
                          border: Border.all(width: 1.w, color: Colors.black),
                        ),
                        child:
                            Icon(Icons.people)
                                .iconSize(16.sp)
                                .iconColor(Color(0xFFFD66CD))
                                .center(),
                      ),
                      SizedBox(width: 8.w),
                      Text(
                        'Limit: ',
                      ).fontSize(12.sp).textColor(Colors.grey[600]),
                      Text('${team.maxMembers} people')
                          .fontSize(12.sp)
                          .fontFamily('PoetsenOne')
                          .fontWeight(FontWeight.bold)
                          .textColor(Colors.black),
                    ].toRow(),
                    SizedBox(height: 6.h),
                    [
                      Container(
                        width: 20.w,
                        height: 20.w,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: Color(0xFFFDF5E1),
                          border: Border.all(width: 1.w, color: Colors.black),
                        ),
                        child:
                            Icon(Icons.access_time)
                                .iconSize(14.sp)
                                .iconColor(Color(0xFFFD66CD))
                                .center(),
                      ),
                      SizedBox(width: 8.w),
                      Text(
                        'Entry deadline: ',
                      ).fontSize(12.sp).textColor(Colors.grey[600]),
                      Text(team.registrationDeadline.toString().split(' ')[0])
                          .fontSize(12.sp)
                          .fontFamily('PoetsenOne')
                          .fontWeight(FontWeight.bold)
                          .textColor(Colors.black),
                    ].toRow(),
                    SizedBox(height: 12.h),
                    [
                      [
                        Container(
                          width: 32.w,
                          height: 32.w,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            image: DecorationImage(
                              image: AssetImage(creator.avatar),
                              fit: BoxFit.cover,
                            ),
                          ),
                        ),
                        SizedBox(width: 8.w),
                        Text(creator.username)
                            .fontSize(14.sp)
                            .textColor(Colors.black)
                            .fontFamily('PoetsenOne'),
                      ].toRow(),
                      Spacer(),
                      Container(
                        width: 90.w,
                        height: 36.h,
                        decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage(
                              'assets/resources/chat_button.png',
                            ),
                            fit: BoxFit.fill,
                          ),
                        ),
                      ).inkWell(onTap: () => _handleTeamAction(team)),
                    ].toRow(),
                  ].toColumn(crossAxisAlignment: CrossAxisAlignment.start),
                ),
              ].toRow(),
              Spacer(),
              _buildTeamIndicator(
                ref.watch(userTeamsProvider(currentUser?.id ?? '')).length,
              ),
            ]
            .toColumn(crossAxisAlignment: CrossAxisAlignment.start)
            .padding(right: 16.w, bottom: 10.h),
      ),
    );
  }

  Widget _buildTeamIndicator(int teamCount) {
    return [
      for (int i = 0; i < teamCount; i++)
        Container(
          width: i == _currentTeamIndex ? 12.w : 6.w,
          height: 6.w,
          margin: EdgeInsets.symmetric(horizontal: 2.w),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(3.r),
            color: i == _currentTeamIndex ? Color(0xFFFD66CD) : Colors.white,
          ),
        ),
    ].toRow(mainAxisAlignment: MainAxisAlignment.center);
  }

  void _showClearMessagesDialog() {
    PopupHelper.showClearMessagesDialog(
      context,
      onConfirmPressed: _clearAllUnreadMessages,
      onCancelPressed: () {},
    );
  }

  Future<void> _clearAllUnreadMessages() async {
    final currentUser = ref.read(currentUserProvider);
    if (currentUser != null) {
      final privateChatNotifier = ref.read(privateChatProvider.notifier);
      final conversations = privateChatNotifier.getUserConversations(
        currentUser.id,
      );

      final List<Future<bool>> clearTasks = [];
      for (final conversation in conversations) {
        if (conversation.unreadCount > 0) {
          clearTasks.add(
            privateChatNotifier.markMessagesAsRead(
              conversationId: conversation.conversationId,
              userId: currentUser.id,
            ),
          );
        }
      }

      if (clearTasks.isNotEmpty) {
        await Future.wait(clearTasks);

        if (mounted) {
          setState(() {});
        }
      }

      if (mounted) {
        ToastHelper.success(
          'All new message notifications cleared',
          context: context,
        );
      }
    }
  }

  void _handleTeamAction(dynamic team) {
    GoRouter.of(context).push(
      '/group-chat',
      extra: {'teamId': team.teamId, 'chatGroupId': team.chatGroupId},
    );
  }

  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final difference = now.difference(time);

    if (difference.inSeconds < 60) {
      return 'Just now';
    } else if (difference.inMinutes < 60) {
      return '${difference.inMinutes}min ago';
    } else if (difference.inHours < 24) {
      return '${difference.inHours}hours ago';
    } else {
      return '${difference.inDays}days ago';
    }
  }
}
